package com.swy.shopgroup.view;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

import com.bumptech.glide.Glide;
import com.google.gson.Gson;
import com.sl.utakephoto.compress.CompressConfig;
import com.sl.utakephoto.exception.TakeException;
import com.sl.utakephoto.manager.ITakePhotoResult;
import com.sl.utakephoto.manager.UTakePhoto;
import com.swy.shopgroup.R;
import com.swy.shopgroup.Utils;
import com.swy.shopgroup.entity.ResultBean;
import com.swy.shopgroup.entity.ShopInfo;
import com.swy.shopgroup.entity.ShopUser;
import com.swy.shopgroup.network.NetAdress;
import com.swy.shopgroup.network.OkHttp;

import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.Objects;

import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;
import okhttp3.Response;

public class HomeFragment extends Fragment {

    private EditText phoneNum, nickEdit;
    private ImageView icon, sex;
    private File uploadIcon, uploadPage;
    private Button register;

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View v = inflater.inflate(R.layout.fragment_home, container, false);
        Utils.checkAllPer(getActivity());
        initView(v);
        initData();
        return v;
    }

    public void initView(View v) {
        phoneNum = v.findViewById(R.id.phoneNum);
        nickEdit = v.findViewById(R.id.nickEdit);
        sex = v.findViewById(R.id.sex);
        icon = v.findViewById(R.id.icon);
        register = v.findViewById(R.id.register);
    }

    public void initData() {
        selectShopInfo();
        icon.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                UTakePhoto.with(getActivity()).openAlbum()
                        .setCompressConfig(new CompressConfig.Builder().create())
                        .build(new ITakePhotoResult() {
                            @Override
                            public void takeSuccess(List<Uri> uriList) {
                                Uri uri = uriList.get(0);
                                uploadIcon = new File(Objects.requireNonNull(uri.getPath()));
                                Bitmap bitmap = BitmapFactory.decodeFile(uri.getPath());
                                icon.setImageBitmap(bitmap);
                            }

                            @Override
                            public void takeFailure(TakeException ex) {

                            }

                            @Override
                            public void takeCancel() {

                            }
                        });
            }
        });
        sex.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                UTakePhoto.with(getActivity()).openAlbum()
                        .setCompressConfig(new CompressConfig.Builder().create())
                        .build(new ITakePhotoResult() {
                            @Override
                            public void takeSuccess(List<Uri> uriList) {
                                Uri uri = uriList.get(0);
                                uploadPage = new File(Objects.requireNonNull(uri.getPath()));
                                Bitmap bitmap = BitmapFactory.decodeFile(uri.getPath());
                                sex.setImageBitmap(bitmap);
                            }

                            @Override
                            public void takeFailure(TakeException ex) {

                            }

                            @Override
                            public void takeCancel() {

                            }
                        });
            }
        });
        register.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                register();
            }
        });
    }

    @SuppressLint("CheckResult")
    public void selectShopInfo() {
        Observable.create(new ObservableOnSubscribe<String>() {
            @Override
            public void subscribe(ObservableEmitter<String> e) throws Exception {
                OkHttp o = new OkHttp();
                try {
                    Response response = o.shopSelectByUser(Utils.getUserToken(getContext()).getData().getId() + "");
                    e.onNext(response.body().string());
                } catch (IOException a) {
                    a.printStackTrace();
                    e.onNext("s");
                }
            }
        }).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe(new io.reactivex.functions.Consumer<String>() {
            @Override
            public void accept(@io.reactivex.annotations.NonNull String s) throws Exception {
                try {
                    Gson gson = new Gson();
                    ResultBean result = gson.fromJson(s, ResultBean.class);
                    if (result.getCode().equals("200")) {
                        register.setVisibility(View.GONE);
                        ShopInfo shopInfo = gson.fromJson(s, ShopInfo.class);
                        ShopInfo.DataBean bean = shopInfo.getData();
                        phoneNum.setText(bean.getName());
                        nickEdit.setText(bean.getShopinfo());
                        Glide.with(getContext()).load(NetAdress.upload + bean.getIcon()).into(icon);
                        Glide.with(getContext()).load(NetAdress.upload + bean.getPagecode()).into(sex);
                        Utils.setAllInfo(getContext(), s, Utils.shopInfo);
                    } else {
                        register.setVisibility(View.VISIBLE);
                    }
//                    Toast.makeText(getContext(), result.getMsg(), Toast.LENGTH_SHORT).show();
                } catch (Exception e) {

                }
            }
        });
    }

    @SuppressLint("CheckResult")
    public void register() {
        final ShopInfo info = new ShopInfo();
        ShopInfo.DataBean bean = new ShopInfo.DataBean();
        String name = phoneNum.getText().toString();
        if (TextUtils.isEmpty(name)) {
            Toast.makeText(getContext(), "请输入店铺名称", Toast.LENGTH_SHORT).show();
            return;
        }
        bean.setName(name);
        String nick = nickEdit.getText().toString();
        if (TextUtils.isEmpty(nick)) {
            Toast.makeText(getContext(), "请输入店铺简介", Toast.LENGTH_SHORT).show();
            return;
        }
        bean.setShopinfo(nick);
        if (uploadIcon == null) {
            Toast.makeText(getContext(), "请上传店铺头像", Toast.LENGTH_SHORT).show();
            return;
        }
        bean.setIcon("");
        if (uploadPage == null) {
            Toast.makeText(getContext(), "请上传营业执照", Toast.LENGTH_SHORT).show();
            return;
        }
        bean.setPagecode("");
        bean.setState(0);
        bean.setUserid(Utils.getUserToken(getContext()).getData().getId());
        info.setData(bean);
        Observable.create(new ObservableOnSubscribe<String>() {
            @Override
            public void subscribe(ObservableEmitter<String> e) throws Exception {
                OkHttp o = new OkHttp();
                try {
                    Response response = o.shopRegister(uploadIcon, uploadPage, info);
                    e.onNext(response.body().string());
                } catch (IOException a) {
                    a.printStackTrace();
                    e.onNext("s");
                }
            }
        }).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe(new io.reactivex.functions.Consumer<String>() {
            @Override
            public void accept(@io.reactivex.annotations.NonNull String s) throws Exception {
                try {
                    Gson gson = new Gson();
                    ResultBean result = gson.fromJson(s, ResultBean.class);
                    if (result.getCode().equals("200")) {
                        register.setVisibility(View.GONE);
                    }
                    Toast.makeText(getContext(), result.getMsg(), Toast.LENGTH_SHORT).show();
                } catch (Exception e) {
                }
            }
        });
    }
}
